import os
import re
import subprocess
import sys
from pathlib import Path

from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion

PYTHON = f"python{sys.version_info[0]}.{sys.version_info[1]}"

BLACK, RED, GREEN, ORANGE, BLUE, MAGENTA, CYAN, GREY = range(8)
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"

def colorize(string, color, bold=False):
    color_code = COLOR_SEQ % (30 + color)
    if bold:
        color_code = BOLD_SEQ + color_code
    return color_code + string + RESET_SEQ


with open('README.md', 'r') as readme_file:
    long_description = readme_file.read()


class CMakeExtension(Extension):
    """
    用于表示一个需要构建的模块
    """
    def __init__(self, name, sourcedir=''):
        """
        _summary_

        Parameters:
        - name : str, cmakelist.txt中的target名称
        - sourcedir : str, optional, default: '', 用于构建扩展CMakelists.txt的目录
        """
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)


class CMakeBuild(build_ext):
    def run(self):
        # 检查 cmake 版本
        try:
            out = subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError(
                'CMake must be installed to build the following extensions: ' +
                ', '.join(e.name for e in self.extensions)
            )

        cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)', out.decode()).group(1))
        if cmake_version < LooseVersion('3.10.0'):
            raise RuntimeError('CMake >= 3.10.0 is required')

        # 构建每一个扩展
        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        extdir = Path(self.get_ext_fullpath(ext.name)).parent.absolute()  # .so 输出目录 build/lib.linux-x86_64-3.9
        build_type = os.environ.get('BUILD_TYPE', 'Release')
        build_args = ['--config', build_type]
        cmake_args = [
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + f"{extdir}{os.path.sep}",
            '-DPYTHON_EXECUTABLE={}'.format(sys.executable),
            '-DEXAMPLE_VERSION_INFO={}'.format(self.distribution.get_version()),
            '-DCMAKE_BUILD_TYPE=' + build_type,
            '-DUSE_PYTHON_EXTENSION=OFF',
            '-DBUILD_EXAMPLES=OFF',
            '-DBUILD_TESTS=OFF',
            '-DBUILD_SHARED_LIBS=OFF',
            '-DCMAKE_BUILD_WITH_INSTALL_RPATH=TRUE',
            '-DCMAKE_INSTALL_RPATH={}'.format('$ORIGIN'), # 表示
            '-DCMAKE_POSITION_INDEPENDENT_CODE=ON',
            f"-Dpybind11_DIR={os.environ.get('CONDA_PREFIX', '.')}/lib/{PYTHON}/site-packages/pybind11/share/cmake/pybind11",
        ]
        print(colorize('* Ext:', GREEN), ext.name)
        print(colorize('* Ext_dir:', GREEN), str(extdir)) # build/lib.linux-x86_64-3.9
        print(colorize('* Build_temp:', GREEN), self.build_temp, '\n') # build/temp.linux-x86_64-3.9
        for arg in cmake_args:
            print(colorize(arg, GREEN))

        # 确保构建目录存在
        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)

        # cmake 构建
        subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp)
        subprocess.check_call(['cmake', '--build', '.', '--target', ext.name] + build_args, cwd=self.build_temp)


setup(
    name='frankx',
    version='0.2.0',
    description='High-Level Motion Library for the Franka Panda Robot',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Lars Berscheid',
    author_email='lars.berscheid@kit.edu',
    url='https://github.com/pantor/frankx',
    packages=find_packages(),
    license='LGPL',
    ext_modules=[CMakeExtension('_frankx'), CMakeExtension('pyaffx')],
    cmdclass=dict(build_ext=CMakeBuild),
    keywords=['robot', 'robotics', 'trajectory-generation', 'motion-control'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering',
        'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
        'Programming Language :: C++',
    ],
    python_requires='>=3.6',
    zip_safe=False,
)
